<template>
  <div class="ct">
    <el-backtop :right="100" :bottom="100">
      <div
        style="
          height: 100%;
          width: 100%;
          background-color: #8c8bff;
          box-shadow: var(--el-box-shadow-lighter);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        "
      >
        <el-icon color="#fff" size="24"><ArrowUpBold /></el-icon>
      </div>
    </el-backtop>
    <div class="title-container">
      <div class="title" @click="setLang">
        {{ bank_id == -1 ? t("generateProblem.title") : "编辑测验：" + bank_name }}
      </div>
      <div class="title-btns">
        <!-- <div style="display: flex">
          <span class="jump-hint">跳转到第</span>
          <el-input-number
            v-model="jumpid"
            :min="0"
            :max="generateList.length"
          />
          <span class="jump-hint-end">题</span>
        </div> -->
        <!-- <el-link :href="'#' + jumpid">
          <el-button
            color="blue"
            size="large"
            style="margin-right: 20px; color: #fff"
          >
            跳转
          </el-button>
        </el-link> -->

        <el-dropdown>
          <el-button color="#8c8bff" plain size="large">
            {{ t("generateProblem.export_btn") }}<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="download('docx')"
                ><div class="output-item">
                  <img src="../assets/word.png" alt="" class="output-icon" />
                  <div class="output-info">docx</div>
                </div></el-dropdown-item
              >
              <el-dropdown-item @click="download('json')"
                ><div class="output-item">
                  <img src="../assets/json.png" alt="" class="output-icon" />
                  <div class="output-info">json</div>
                </div></el-dropdown-item
              >
              <el-dropdown-item @click="download('xlsx')"
                ><div class="output-item">
                  <img src="../assets/xlsx.png" alt="" class="output-icon" />
                  <div class="output-info">excel</div>
                </div></el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          color="#8c8bff"
          size="large"
          @click="publish_confirm()"
          :disabled="generateList.length == 0"
          style="margin-left: 10px; color: #fff"
        >
        {{ t("generateProblem.publish_btn") }}
        </el-button>
      </div>
    </div>

    <el-row style="margin: 0">
      <el-col :span="8">
        <div class="generate-left">
          <div v-if="isLoading" class="first-message">
            <VueSpinnerPie size="40" color="white" />&nbsp
            新的题目正在生成中，这可能需要1-3分钟，请稍等……
          </div>
          <div v-else :class="bank_id==-1?'first-message':'first-message next-message'">
            <el-icon size="28" color="#ffffff"><Warning /></el-icon>
            <span style="font-size: 16px; text-align: left; padding-left: 20px">
              {{ bank_id==-1?t("generateProblem.form_hint"):'填写表单并点击生成按钮，以向您的测验中追加习题。您可以自由地排序、编辑、删除这些习题。' }}
            </span>
          </div>
          <form class="form">
            <el-row :gutter="10">
              <el-col :span="24">
                <label>{{ t("generateProblem.knowledge") }}</label>
                <div>
                  <el-cascader
                    @change="name=form.knowledge"
                    size="large"
                    :show-all-levels="false"
                    v-model="form.knowledge"
                    :options="topicOptions"
                    clearable
                    :placeholder="t('generateProblem.placeholder') "
                    style="
                      width: 100%;
                      --el-select-input-focus-border-color: #8c8bff;
                    "
                  />
                  
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <div>
                  <label>{{ t("generateProblem.question_type") }} </label>
                  <div>
                    <el-select
                      v-model="form.type"
                      size="large"
                      :placeholder="t('generateProblem.placeholder') "
                      style="
                        width: 240px;
                        --el-select-input-focus-border-color: #8c8bff;
                      "
                    >
                      <el-option
                        v-for="item in typeOptions_en"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <label>{{ t("generateProblem.quantity") }} </label>
                <div>
                  <el-select
                    v-model="form.cnt"
                    class="m-2"
                    placeholder="Select"
                    size="large"
                    style="
                      width: 240px;
                      --el-select-input-focus-border-color: #8c8bff;
                    "
                  >
                    <el-option
                      v-for="item in cntOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </el-col>
            </el-row>

            <el-row :gutter="10">
              <el-col :span="12">
                <label>{{ t("generateProblem.difficulty") }}</label>
                <div>
                  <el-select
                    v-model="form.difficulty"
                    class="m-2"
                    placeholder="Select"
                    size="large"
                    style="width: 240px; --el-switch-on-color: #8c8bff"
                  >
                    <el-option
                      v-for="item in difficultyOptions_en"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div> </el-col
            ></el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <label>{{ t("generateProblem.contextualized") }}</label>
                <div>
                  <el-switch
                    v-model="form.isScene"
                    size="large"
                    style="--el-switch-on-color: #8c8bff"
                  />
                  <small
                    :class="form.isScene ? 'scene-info-active' : 'scene-info'"
                    >{{
                      form.isScene
                        ? t("generateProblem.contextualized_hint")
                        : "不会刻意生成生活情境类题目"
                    }}</small
                  >
                </div>
              </el-col>
            </el-row>
            <div>
              <label>{{ t("generateProblem.other_restriction") }}</label>
              <div>
                <el-input
                  v-model="form.otherRestriction"
                  :autosize="{ minRows: 3 }"
                  type="textarea"
                  :placeholder="t('generateProblem.other_placeholder') "
                  style="--el-input-focus-border-color: #8c8bff"
                />
              </div>
            </div>
            <div>
              <el-button
                color="#8c8bff"
                size="large"
                style="
                  color: #fff;
                  width: 100%;
                  height: 60px;
                  font-size: 20px;
                  border-radius: 10px;
                  margin-top: 20px;
                "
                @click="generate()"
              >
                {{ t("generateProblem.generate_btn") }}
              </el-button>
            </div>
          </form>
        </div>
      </el-col>
      <el-col :span="16">
        <div style="padding: 20px; padding-bottom: 150px">
          <div class="omit" v-if="generateList.length == 0 && !isLoading">
            {{ t("generateProblem.right_placeholder") }}^-^
          </div>
          <div v-if="generateList.length == 0 && isLoading">
            <el-card class="brick"><el-skeleton :rows="5" animated /></el-card>
            <el-card class="brick"><el-skeleton :rows="5" animated /></el-card>
            <el-card class="brick"><el-skeleton :rows="5" animated /></el-card>
            <el-card class="brick"><el-skeleton :rows="5" animated /></el-card>
          </div>
          <draggable
            :list="generateList"
            item-key="id"
            class="list-group"
            ghost-class="ghost"
            :move="checkMove"
            @end="onEnd"
            v-bind="dragOptions"
            :disabled="editIndex>=0"
          >
            <template #item="{ element }">
              <div class="list-group-item">
                <el-card v-if="editIndex != element.index">
                  <div class="question-title">
                    {{ element.index + 1 + "&nbsp;." + element.content }}
                  </div>
                  <div
                    class="question-option"
                    v-for="(opt, key) in element.options"
                  >
                    <input
                      type="radio"
                      :name="element.id"
                      :value="key"
                      style="height: 25px; width: 25px"
                      @change="answer_generated(element.index, key)"
                    />
                    <label style="padding-left: 10px">{{
                      key + ")&nbsp;"
                    }}</label
                    ><label v-html="updateMarkdown(opt)"></label>
                  </div>
                  <div
                    :hidden="element.selected == 0 || element.selected == -1"
                    class="answer"
                  >
                    <div
                      :class="
                        element.selected == element.correct_answer
                          ? 'answer-tip'
                          : 'answer-tip-fail'
                      "
                    >
                      {{
                        element.selected == element.correct_answer
                          ? "正确！"
                          : "哎呀！回答错误，正确答案为：" +
                            element.correct_answer
                      }}
                    </div>
                    <div
                      v-if="
                        element.description != null && element.description != ''
                      "
                      class="answer-desc"
                      v-html="updateMarkdown(element.description)"
                    ></div>
                  </div>

                  <div class="question-bottom">
                    <div class="left">
                      <el-tooltip content="点击上移" placement="top">
                        <el-icon
                          @click="moveUp(element.index)"
                          size="30"
                          color="#999"
                          ><ArrowUp
                        /></el-icon>
                      </el-tooltip>
                      <el-tooltip content="点击下移" placement="top">
                        <el-icon
                          @click="moveDown(element.index)"
                          size="30"
                          color="#999"
                          ><ArrowDown
                        /></el-icon>
                      </el-tooltip>
                    </div>
                    <div class="right">
                      <el-tooltip
                        content="不满意？重新生成这道题目"
                        placement="top"
                      >
                        <el-icon
                          @click="
                            regenerateIndex = element.index;
                            regenerateVisible = true;
                          "
                          size="30"
                          color="#999"
                          ><RefreshLeft
                        /></el-icon>
                      </el-tooltip>
                      <el-tooltip content="手动编辑这道题目" placement="top">
                        <el-icon
                          @click="edit(element.index)"
                          size="30"
                          color="#999"
                          ><EditPen
                        /></el-icon>
                      </el-tooltip>
                      <el-tooltip content="删除这道题目" placement="top">
                        <el-icon
                          @click="
                            deleteIndex = element.index;
                            deleteVisible = true;
                          "
                          size="30"
                          color="#999"
                          ><Delete
                        /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                </el-card>
                <el-card v-else>
                  <div class="edit-title">{{t("generateProblem.stem") }}</div>
                  <el-input
                    v-model="element.content"
                    placeholder="请输入题目的题面"
                    :autosize="{ minRows: 4, maxRows: 6 }"
                    type="textarea"
                    style="font-size: 16px;"
                  />
                  
                  <div
                    class="edit-option"
                    v-for="(opt, key) in element.options"
                  >
                  <div class="edit-title">{{t("generateProblem.alternative") +" " + key }}</div>
                    <div>
                      <el-input
                      v-model="element.options[key]"
                      placeholder="请输入题目的选项"
                      style="font-size: 16px;height:50px;--el-input-focus-border-color: #8c8bff;"
                    />
                    </div>
                  </div>
                  <div class="edit-title">{{t("generateProblem.correct_answer") }}</div>
                  <el-select
                    v-model="element.correct_answer"
                    placeholder="Select"
                    size="large"
                    style="
                      font-size: 16px;
                      width: 100%;
                      --el-select-input-focus-border-color: #8c8bff;
                    "
                  >
                    <el-option
                      v-for="(opt,key) in element.options"
                      :key="key"
                      :label="key+') '+opt"
                      :value="key"
                    />
                  </el-select>
                  <div class="edit-title">{{t("generateProblem.description") }}</div>
                  <el-input
                      v-model="element.description"
                      placeholder="请输入题目的解析"
                      :autosize="{ minRows: 4, maxRows: 6 }"
                      type="textarea"
                    />

                  <div class="question-bottom">
                    <div class="right">
                      <el-button size="large" type="info" plain @click="redoEdit();">{{t("generateProblem.cancel_btn") }}</el-button>
                      <el-button
                        color="#8c8bff"
                        style="color: #fff"
                        size="large"
                        @click="commitEdit();"
                      >
                      {{t("generateProblem.confirm_btn") }}
                      </el-button>
                    </div>
                  </div>
                </el-card>
              </div>
            </template>
          </draggable>
        </div>
      </el-col>
    </el-row>
    <!-- 发布练习对话框 -->
    <el-dialog
      :show-close="false"
      v-model="dialogFormVisible"
      width="50%"
      style="border-radius: 8px;padding: 20px 20px;"
    >
    <p class="dialog-hint">
        您正在发布练习，请填写完成练习的限制时间。
    </p>
    <p class="dialog-hint">
      我们将生成一个链接供学生做题，
      将链接复制给学生并打开链接就可以开始练习啦:）！
    </p>
      <el-form :model="form">
        <div class="publish-form-item">
          <div class="publish-form-info">练习时长限制</div>
          <el-time-picker v-model="time" placeholder="不限时" />
        </div>
        <div class="publish-form-item">
          <div class="publish-form-info">给你的练习起个名字</div>
          <el-input v-model="name" placeholder="请输入你的练习的名字" />
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            plain
            color="#8c8bff"
            class="btn-cancel"
            @click="dialogFormVisible = false"
            >取消</el-button
          >
          <el-button
            :dark="isDark"
            color="#626aef"
            class="btn-confirm"
            @click="publish_problem()"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 发布成功回复对话框 -->
    <el-dialog v-model="dialogVisible" title="Tips" width="30%">
      <p class="confirm-hint">
        复制链接
        <span class="link"
          >{{ $FRONT_URL }}/exercise?bankId={{ bank_id }}&bankName={{
            name
          }}</span
        >
        给你的学生
      </p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="copyLink()">复制</el-button>
          <el-button type="primary" @click="goTo()"> 去试试</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除题目对话框 -->
    <el-dialog
      :show-close="false"
      v-model="deleteVisible"
      width="30%"
      style="border-radius: 8px"
    >
      <p class="dialog-hint">确认要删除此题目吗？此操作无法被撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            plain
            color="#8c8bff"
            class="btn-cancel"
            @click="deleteVisible = false"
            >取消</el-button
          >
          <el-button
            :dark="isDark"
            color="#626aef"
            class="btn-confirm"
            @click="
              deleteItem(deleteIndex);
              deleteVisible = false;
            "
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 重新生成题目对话框 -->
    <el-dialog
      :show-close="false"
      v-model="regenerateVisible"
      width="30%"
      style="border-radius: 8px"
    >
      <p class="dialog-hint">确认要重新生成此题目吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            plain
            color="#8c8bff"
            class="btn-cancel"
            @click="regenerateVisible = false"
            >取消</el-button
          >
          <el-button
            :dark="isDark"
            color="#626aef"
            class="btn-confirm"
            @click="
              regenerate(regenerateIndex);
              regenerateVisible = false;
            "
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useI18n } from "vue-i18n";  // 引用组件
const { t, locale } = useI18n();  // 解构调用函数
function setLang() {
    locale.value = "en"  // 设置语言模式
}
</script>
<script>
import axios from "axios";
import { VueSpinner, VueSpinnerPie } from "vue3-spinners";
import { reactive, ref } from "vue";
import { marked } from "marked";
import "github-markdown-css/github-markdown.css";
import draggable from "vuedraggable";



export default {
  components: {
    VueSpinner,
    VueSpinnerPie,
    draggable,
  },
  data() {
    return {
      jumpid: 0,
      deleteIndex: -1, //待删除的下标
      regenerateIndex: -1, //重新生成的下标
      formLabelWidth: "100px",
      editIndex: -1,
      editHistory: null,
      dialogFormVisible: ref(false),
      dialogVisible: ref(false),
      deleteVisible: ref(false), // 删除题目对话框
      regenerateVisible: ref(false), // 重新生成题目对话框
      time: ref(new Date(2016, 9, 10, 0, 30)),
      topicOptions: [], //主题，有若干级
      cntOptions: [
        {
          value: 3,
          label: "3",
        },
        {
          value: 5,
          label: "5",
        },
        {
          value: 10,
          label: "10",
        },
        {
          value: 15,
          label: "15",
        },
        {
          value: 20,
          label: "20",
        },
        {
          value: 25,
          label: "25",
        },
        {
          value: 30,
          label: "30",
        },
        {
          value: 40,
          label: "40",
        },
      ],
      typeOptions: [
        {
          value: "single choice",
          label: "单项选择",
        },
        {
          value: "fill in the blanks",
          label: "填空",
        },
        {
          value: "True or False",
          label: "判断",
        },
        {
          value: "short answer",
          label: "简答",
        },
      ],
      typeOptions_en: [
        {
          value: "single choice",
          label: "Multiple choices",
        },
        {
          value: "fill in the blanks",
          label: "fill in the blanks",
        },
        {
          value: "True or False",
          label: "True or False",
        },
        {
          value: "short answer",
          label: "short answer",
        },
      ],
      difficultyOptions: [
        {
          value: 0,
          label: "简单",
        },
        {
          value: 1,
          label: "较难",
        },
        {
          value: 2,
          label: "渐增",
        },
      ],
      difficultyOptions_en: [
        {
          value: 0,
          label: "Simple",
        },
        {
          value: 1,
          label: "difficult",
        },
        {
          value: 2,
          label: "increase",
        },
      ],
      form: {
        cnt: 3, // 最大题目数量，any为自动
        knowledge: null, // 主题
        difficulty: 0, // 难度，0容易，1较难，2渐增
        isScene: true, // 是否创设情境
        type: null, // 题型
        otherRestriction: "", // 其他约束
      },
      problemContent: "",
      isLoading: false,
      generateList:[],
      // generateList: [
      //   {
      //     content:
      //       "\u5c0f\u4e3d\u4ece\u5bb6\u91cc\u5e26\u4e8624\u5757\u5c0f\u997c\u5e72\u53bb\u5b66\u6821\u3002\u5982\u679c\u5979\u548c\u670b\u53cb\u4eec\u4e00\u8d77\u5403\u4e86\u4e00\u4e9b\uff0c\u8fd8\u5269\u4e0b15\u5757\u997c\u5e72\uff0c\u90a3\u4e48\u5979\u548c\u670b\u53cb\u4eec\u4e00\u5171\u5403\u4e86\u591a\u5c11\u5757\u997c\u5e72\uff1f",
      //     correct_answer: "A",
      //     description:
      //       "\u5c0f\u4e3d\u4ece\u5bb6\u91cc\u5e26\u4e8624\u5757\u5c0f\u997c\u5e72\u53bb\u5b66\u6821\uff0c\u5979\u548c\u670b\u53cb\u4eec\u4e00\u8d77\u5403\u4e86\u4e00\u4e9b\uff0c\u8fd8\u5269\u4e0b15\u5757\u3002\u901a\u8fc7\u8ba1\u7b9724-9=15\u6765\u5f97\u51fa\u5979\u548c\u670b\u53cb\u4eec\u4e00\u5171\u5403\u4e869\u5757\u997c\u5e72\uff0c\u56e0\u6b64\u7b54\u6848\u662fA\u3002",
      //     edit: 0,
      //     equation: "24-9=15",
      //     id: 61,
      //     like: 0,
      //     options: {
      //       A: "9",
      //       B: "8",
      //       C: "10",
      //     },
      //     selected: -1,
      //     index: 0,
      //   },
      //   {
      //     content:
      //       "\u6770\u514b\u5728\u56fe\u4e66\u9986\u501f\u4e8636\u672c\u4e66\u3002\u5982\u679c\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u4e66\uff0c\u90a3\u4e48\u4ed6\u8fd8\u5269\u4e0b\u591a\u5c11\u672c\u4e66\u9700\u8981\u8bfb\uff1f",
      //     correct_answer: "B",
      //     description:
      //       "\u5728\u56fe\u4e66\u9986\uff0c\u6770\u514b\u501f\u4e8636\u672c\u4e66\uff0c\u5176\u4e2d\u4e00\u4e9b\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u3002\u901a\u8fc7\u51cf\u6cd536-17=19\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u77e5\u6770\u514b\u8fd8\u5269\u4e0b19\u672c\u4e66\u9700\u8981\u8bfb\uff0c\u56e0\u6b64\u7b54\u6848\u662fB\u3002",
      //     edit: 0,
      //     equation: "36-17=19",
      //     id: 62,
      //     like: 0,
      //     options: {
      //       A: "18",
      //       B: "19",
      //       C: "20",
      //     },
      //     selected: -1,
      //     index: 1,
      //   },
      //   {
      //     content:
      //       "\u6770\u514b\u5728\u56fe\u4e66\u9986\u501f\u4e8636\u672c\u4e66\u3002\u5982\u679c\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u4e66\uff0c\u90a3\u4e48\u4ed6\u8fd8\u5269\u4e0b\u591a\u5c11\u672c\u4e66\u9700\u8981\u8bfb\uff1f",
      //     correct_answer: "B",
      //     description:
      //       "\u5728\u56fe\u4e66\u9986\uff0c\u6770\u514b\u501f\u4e8636\u672c\u4e66\uff0c\u5176\u4e2d\u4e00\u4e9b\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u3002\u901a\u8fc7\u51cf\u6cd536-17=19\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u77e5\u6770\u514b\u8fd8\u5269\u4e0b19\u672c\u4e66\u9700\u8981\u8bfb\uff0c\u56e0\u6b64\u7b54\u6848\u662fB\u3002",
      //     edit: 0,
      //     equation: "36-17=19",
      //     id: 63,
      //     like: 0,
      //     options: {
      //       A: "18",
      //       B: "19",
      //       C: "20",
      //     },
      //     selected: -1,
      //     index: 2,
      //   },
      // ],
      // generateList_en: [
      //   {
      //     content:
      //       "Mary brought 24 small cookies from home to school. If she ate some cookies with her friends and there were still 15 cookies left, how many cookies did she eat with her friends in total?",
      //     correct_answer: "A",
      //     description:
      //       "Mary brought 24 small cookies from home to school. She and her friends ate some together, and there were still 15 left. By calculating 24-9=15, it can be concluded that she and her friends ate a total of 9 cookies, so the answer is A.",
      //     edit: 0,
      //     equation: "24-9=15",
      //     id: 61,
      //     like: 0,
      //     options: {
      //       A: "9",
      //       B: "8",
      //       C: "10",
      //     },
      //     selected: -1,
      //     index: 0,
      //   },
      //   {
      //     content:
      //       "\u6770\u514b\u5728\u56fe\u4e66\u9986\u501f\u4e8636\u672c\u4e66\u3002\u5982\u679c\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u4e66\uff0c\u90a3\u4e48\u4ed6\u8fd8\u5269\u4e0b\u591a\u5c11\u672c\u4e66\u9700\u8981\u8bfb\uff1f",
      //     correct_answer: "B",
      //     description:
      //       "\u5728\u56fe\u4e66\u9986\uff0c\u6770\u514b\u501f\u4e8636\u672c\u4e66\uff0c\u5176\u4e2d\u4e00\u4e9b\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u3002\u901a\u8fc7\u51cf\u6cd536-17=19\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u77e5\u6770\u514b\u8fd8\u5269\u4e0b19\u672c\u4e66\u9700\u8981\u8bfb\uff0c\u56e0\u6b64\u7b54\u6848\u662fB\u3002",
      //     edit: 0,
      //     equation: "36-17=19",
      //     id: 62,
      //     like: 0,
      //     options: {
      //       A: "18",
      //       B: "19",
      //       C: "20",
      //     },
      //     selected: -1,
      //     index: 1,
      //   },
      //   {
      //     content:
      //       "\u6770\u514b\u5728\u56fe\u4e66\u9986\u501f\u4e8636\u672c\u4e66\u3002\u5982\u679c\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u4e66\uff0c\u90a3\u4e48\u4ed6\u8fd8\u5269\u4e0b\u591a\u5c11\u672c\u4e66\u9700\u8981\u8bfb\uff1f",
      //     correct_answer: "B",
      //     description:
      //       "\u5728\u56fe\u4e66\u9986\uff0c\u6770\u514b\u501f\u4e8636\u672c\u4e66\uff0c\u5176\u4e2d\u4e00\u4e9b\u4ed6\u5df2\u7ecf\u8bfb\u5b8c\u5e76\u5f52\u8fd8\u4e8617\u672c\u3002\u901a\u8fc7\u51cf\u6cd536-17=19\uff0c\u6211\u4eec\u53ef\u4ee5\u5f97\u77e5\u6770\u514b\u8fd8\u5269\u4e0b19\u672c\u4e66\u9700\u8981\u8bfb\uff0c\u56e0\u6b64\u7b54\u6848\u662fB\u3002",
      //     edit: 0,
      //     equation: "36-17=19",
      //     id: 63,
      //     like: 0,
      //     options: {
      //       A: "18",
      //       B: "19",
      //       C: "20",
      //     },
      //     selected: -1,
      //     index: 2,
      //   },
      // ],
      bank_id: -1,
      bank_name: "",
      name: null,
    };
  },
  computed: {
    dragOptions() {
      return {
        animation: 250,
        group: "question",
        disabled: false,
        ghostClass: "ghost",
      };
    },
  },
  methods: {
    checkMove: function (e) {
      window.console.log("Future index: " + e.draggedContext.futureIndex);
    },
    updateIndex() {
      //更新index
      let len = this.generateList.length;
      for (let i = 0; i < len; i++) {
        this.generateList[i].index = i;
      }
    },
    updateDuration(){
      this.time = ref(new Date(2024, 9, 10, 0, 3*this.generateList.length))
    },
    //拖拽开始的事件
    onStart() {
      this.drag = true;
      console.log("开始拖拽");
    },
    //拖拽结束的事件，更新index
    onEnd() {
      this.drag = false;
      console.log("结束拖拽");
      this.updateIndex()
    },
    moveUp(index) {
      if (index <= 0) return;
      if (this.generateList.length <= 1) return;

      var temp = this.generateList[index];
      this.generateList.splice(index, 1, this.generateList[index - 1]); //上面的换下来
      this.generateList.splice(index - 1, 1, temp); //temp换上去

      this.updateIndex();
    },
    moveDown(index) {
      if (this.generateList.length <= 1) return;
      if (index >= this.generateList.length - 1) return;

      var temp = this.generateList[index];
      this.generateList.splice(index, 1, this.generateList[index + 1]); //下面的换上去
      this.generateList.splice(index + 1, 1, temp); //temp换上去

      this.updateIndex();
    },
    generate() {
      this.isLoading = true;
      const that = this;
      const url = this.$API_URL + "/problem/generate";
      const formData = new FormData();
      console.log(this.form.knowledge);
      // console.log(this.$refs['cascader'].getCheckedNodes())

      formData.append("knowledge", this.form.knowledge);
      formData.append("cnt", 2);
      formData.append("isScene", this.form.isScene);
      formData.append("type", this.form.type);
      formData.append("difficulty", this.form.difficulty);
      formData.append("otherRestriction", this.form.otherRestriction);
      for (var i = 0; i < this.form.cnt; i += 2) {
        // 发送 FormData
        axios
          .post(url, formData)
          .then(function (response) {
            
            that.generateList.push(...response.data);
            that.updateIndex();
            that.updateDuration();
            if (that.form.cnt - that.generateList.length < 1) {
              that.isLoading = false;
              ElNotification({
                title: "成功",
                message: "题目生成成功！",
                type: "success",
              });
            }
          })
          .catch(function (error) {
            console.log(error);

            that.isLoading = false;
            ElNotification({
              type: "error",
              title: "错误",
              message: "题目生成失败！错误信息" + error,
            });
          });
      }
    },
    answer_generated(index, answer) {
      console.log(index);
      this.generateList[index].selected = answer;
    },
    copy_problem() {
      // 将 JSON 数组转换为字符串
      const jsonString = JSON.stringify(this.generateList, null, 2);
      // 使用 Clipboard API 将文本复制到剪贴板
      navigator.clipboard
        .writeText(jsonString)
        .then(() => {
          ElNotification({
            title: "成功",
            message: "题目复制成功！",
            type: "success",
          });
        })
        .catch((err) => {
          ElNotification({
            type: "error",
            title: "错误",
            message: "题目复制失败",
          });
        });
    },
    regenerate(index) {
      this.isLoading = true;
      const that = this;
      const url = this.$API_URL + "/problem/generate";
      const formData = new FormData();
      console.log(this.form.knowledge);
      formData.append("knowledge", this.form.knowledge);
      formData.append("cnt", 1);
      formData.append("isScene", this.form.isScene);
      formData.append("type", this.form.type);
      formData.append("difficulty", this.form.difficulty);
      formData.append("otherRestriction", this.form.otherRestriction);
      // 发送 FormData
      axios
        .post(url, formData)
        .then(function (response) {
          that.generateList.splice(index, 1, response.data); //成功直接用splice替换
          that.updateIndex(); //更新下标
          ElNotification({
            title: "成功",
            message: "题目重新生成成功！",
            type: "success",
          });
        })
        .catch(function (error) {
          console.log(error);
          ElNotification({
            type: "error",
            title: "错误",
            message: "题目重新生成失败！错误信息" + error,
          });
        });
      this.isLoading = false;
    },
    export_problem() {
      const jsonStr = JSON.stringify(this.generateList);
      let dataUri =
        "data:application/json;charset=utf-8," + encodeURIComponent(jsonStr);
      let exportFileDefaultName = "data.json";
      let linkElement = document.createElement("a");
      linkElement.setAttribute("href", dataUri);
      linkElement.setAttribute("download", exportFileDefaultName);
      linkElement.click();
      ElNotification({
        title: "成功",
        message: "题目导出成功！",
        type: "success",
      });
    },
    download(suffix) {
      if (suffix == "json") {
        this.export_problem();
        return;
      }
      const url = this.$API_URL + "/problem/download";
      var publish_list = [];
      for (let item of this.generateList) {
        publish_list.push(item.id);
      }
      const formData = new FormData();
      for (let id of publish_list) {
        formData.append("exportList[]", id);
      }
      formData.append("suffix", suffix);
      console.log(formData);

      axios
        .post(url, formData, {
          responseType: "blob",
        })
        .then(function (response) {
          // 处理响应，例如创建一个用于下载的URL
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "exercise." + suffix); // 或者其他的文件名
          document.body.appendChild(link);
          link.click();
          ElNotification({
            title: "成功",
            message: "题目导出成功！",
            type: "success",
          });
        })
        .catch(function (error) {
          console.error("下载错误:", error);
          ElNotification({
            type: "error",
            title: "错误",
            message: "题目导出失败！错误信息" + error,
          });
        });
    },
    edit(index) {
      this.editIndex=index;
      this.editHistory=this.generateList[index];
      //this.generateList[index].edit = 1 - this.generateList[index].edit;
    },
    redoEdit(){
      this.generateList[this.editIndex]=this.editHistory;
      this.editIndex=-1;
    },
    commitEdit(){
      let url= this.$API_URL + "/problem/edit";

      const element=this.generateList[this.editIndex];

      const formData = new FormData();
      
      formData.append("optionList[]", element.options.A);
      formData.append("optionList[]", element.options.B);
      formData.append("optionList[]", element.options.C);

      formData.append("user_id", 1);
      formData.append("question_id", element.question_id);
      formData.append("question_content", element.content);
      formData.append("correct_answer", element.correct_answer);
      formData.append("description", element.description);

      const that = this;
      axios
        .post(url, formData)
        .then(function (response) {
          ElMessage({
            message: "题目修改成功",
            type: "success",
          });
        })
        .catch(function (error) {
          console.log(error);
          ElNotification({
            type: "error",
            title: "错误",
            message: "题目修改失败！错误信息" + error,
          });
        });

      this.generateList[this.editIndex].selected=-1;
      this.editIndex=-1;
    },
    publish_confirm() {
      this.dialogFormVisible = true;
    },
    publish_problem() {
      this.dialogFormVisible = false;
      var publish_list = [];
      for (let item of this.generateList) {
        publish_list.push(item.id);
      }

      const url = this.$API_URL + "/problem/store";
      const formData = new FormData();
      for (let id of publish_list) {
        formData.append("exportList[]", id);
      }
      const that = this;
      formData.append("user_id", 1);
      formData.append("name", this.name);
      formData.append("hour", this.time.getHours());
      formData.append("minute", this.time.getMinutes());
      formData.append("second", this.time.getSeconds());
      axios
        .post(url, formData)
        .then(function (response) {
          that.bank_id = response.data.bank_id;
          that.dialogFormVisible = false;
          that.dialogVisible = true;
          ElNotification({
            title: "成功",
            message: "题目发布成功！",
            type: "success",
          });
        })
        .catch(function (error) {
          console.log(error);
          that.isLoading = false;
          ElNotification({
            type: "error",
            title: "错误",
            message: "题目发布失败！错误信息" + error,
          });
        });
    },
    copyLink() {
      const link =
        this.$FRONT_URL +
        "/exercise?bankId=" +
        this.bank_id +
        "&bankName=" +
        this.name;
      // 使用 Clipboard API 将文本复制到剪贴板
      navigator.clipboard
        .writeText(link)
        .then(() => {
          ElNotification({
            title: "成功",
            message: "链接复制成功！",
            type: "success",
          });
        })
        .catch((err) => {
          ElNotification({
            type: "error",
            title: "错误",
            message: "链接复制失败" + err,
          });
        });
    },
    goTo() {
      const that = this;
      window.open(
        this.$FRONT_URL +
          "/exercise?bankId=" +
          this.bank_id +
          "&bankName=" +
          this.name
      );
    },
    loadBankDetails(bankId) {
      console.log("loadBankDetails succeed");
      const url = this.$API_URL + "/problem/getBankDetails/" + bankId;

      // 发起请求到后端获取教案详细信息，然后填充到表单中
      axios
        .get(url, {
          headers: {
            "ngrok-skip-browser-warning": "true",
          },
        })
        .then((response) => {
          // this.form = response.data.form;
          this.generateList = response.data.selected_questions;
          this.updateIndex();
          console.log(this.generateList);
          // this.generateList = response.data.selected_questions;  // 设置选定的问题列表
        })
        .catch((error) => {
          console.error("Error fetching bank details:", error);
        });
    },
    loadTopic() {
      console.log("load topic");
      const url = this.$API_URL + "/problem/topic";

      // 发起请求到后端获取教案详细信息，然后填充到表单中
      axios
        .get(url, {
          headers: {
            "ngrok-skip-browser-warning": "true",
          },
        })
        .then((response) => {
          this.topicOptions = response.data.topics;
        })
        .catch((error) => {
          console.error("Error fetching topic:", error);
        });
    },
    updateMarkdown(content) {
      return marked(content);
    },
    deleteItem(index) {
      this.generateList.splice(index, 1);
      this.updateIndex(); //更新下标
      ElNotification({
        title: "成功",
        message: "题目删除成功！",
        type: "success",
      });
    },
  },
  mounted() {
    console.log("mounted succeed");
    const bankId = this.$route.query.bankId;
    console.log(bankId);
    if (bankId) {
      this.loadBankDetails(bankId);
      this.bank_id = bankId;
      this.bank_name = this.$route.query.bankName;
    }
    this.loadTopic();
  },
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.el-icon-circle-check {
  color: #aaa;
  width: 16px;
  height: 16px;
}
.title-bar {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
}

.problem-content {
  font-weight: 700;
  margin: 5px;
}
.answer {
  text-align: left;
  font-weight: normal;
  margin-top: 10px;
}

.answer .answer-tip {
  font-weight: 700;
  font-size: 22px;
  height: 30px;
  line-height: 30px;
  color: #67c23a;
}

.answer .answer-tip-fail {
  font-weight: 700;
  font-size: 22px;
  height: 30px;
  line-height: 30px;
  color: #f56c6c;
}

.title-container {
  background-color: #ffffff;
  border-bottom: 1px solid #ccc;
  overflow: hidden;
  position: sticky;
  top: 0px;
  z-index: 30;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  padding: 0 40px 0 20px;
}
.brick {
  margin: 20px 0px;
}
.jump-hint {
  width: 70px;
  margin: 10px;
}
.title {
  box-sizing: border-box;
  margin: 0;

  color: #555;
  font-size: 28px;
  font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
    "Lucida Sans", Arial, sans-serif;
  font-weight: bolder;
  text-align: left;
}
.jump-hint-end {
  width: 30px;
  margin: 10px;
}

.title-btns {
  display: flex;
}
.form {
  margin: 10px;
  text-align: left;
}
.check {
  width: 20px;
  height: 20px;
  border: #bbb 2px solid;
  cursor: pointer;
}
.check:hover {
  border: #00aa00 2px solid;
}
.generate-problem-list {
  text-align: left;
  margin: 20px;
  border: #bbb 1px solid;
  padding: 10px 20px;
  width: 50%;
  min-height: 200px;
}
.option {
  margin: 5px;
  color: #888;
}
.transfer {
  margin: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.omit {
  font-size: 28px;
  color: #888;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 350px;
}
.link {
  color: blueviolet;
}
.row {
  width: 60%;
  margin: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.form label {
  font-size: 20px;
  display: block;
  height: 50px;
  line-height: 50px;
  color: #555;
  font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
    "Lucida Sans", Arial, sans-serif;
  font-weight: bolder;
}
.problem-title {
  font-weight: 700;
  color: #888;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.hint {
  color: #bbb;
  font-size: 16px;
}
.form-item {
  text-align: left;
}
.el-row {
  margin: 20px;
}
select {
  width: 170px;
  font-size: 16px;
  height: 21.33px;
}
.problem {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
}

.submit-btn {
  width: 100px;
  height: 40px;
  border-radius: 5px;
  border-style: none;
  background-color: #4095e5;
  color: #fff;
  line-height: 40px;
  font-weight: 700;
  cursor: pointer;
  text-align: center;
  font-size: 20px;
  margin: 20px;
}
.submit-btn:hover {
  background-color: #4055e5;
}
.publish-btn {
  background-color: #00aa00;
}
.publish-btn:hover {
  background-color: #075a07;
}
.publish-btn:disabled {
  background-color: #bbb;
  cursor: not-allowed;
}
.transfer-btn {
  width: 100px;
  height: 40px;
  border-radius: 5px;
  border-style: none;
  background-color: cadetblue;
  color: #fff;
  line-height: 40px;
  font-weight: 700;
  cursor: pointer;
  text-align: center;
  font-size: 16px;
  margin: 20px;
}
.transfer-btn:disabled {
  background-color: #bbb;
  cursor: not-allowed;
}
.submit {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
}

input {
  appearance: none;

  border-radius: 50%;
  width: 16px;
  height: 16px;

  border: 1px solid #a6a5fa;
  transition: 0.2s all linear;
  margin-right: 5px;

  position: relative;

  vertical-align: middle;
}

input:checked {
  border: 6px solid #8c8bff;
}
.button-group {
  display: flex;
  justify-content: right;
  padding: 10px 100px;
}
.confirm-hint {
  text-align: left;
  font-size: 16px;
  line-height: 1.5;
  margin-top: 0px;
  margin-bottom: 20px;
}

.first-message {
  background-color: #a6a5fa;
  border-radius: 8px;
  color: #ffffff;
  align-items: center;
  display: flex;
  box-sizing: border-box;
  padding: 15px;
  line-height: 2;
}
.next-message{
  background-color: #79bbff;
}

.generate-left {
  background-color: #ffffff;
  box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.15);
  padding: 20px;
  overflow: hidden;
  // height: 100%;
  box-sizing: border-box;
  position:sticky;
  top: 70px;
  // display:sticky;

}

.ct {
  background-color: #f5f7fa;
}

.scene-info {
  margin-left: 20px;
  font-size: 14px;
  color: #999;
}

.scene-info-active {
  margin-left: 20px;
  font-size: 14px;
  color: #8c8bff;
}

.question-option {
  display: flex;
  align-items: center;
  text-align: left;
  height: 50px;
  font-size: 24px;
  margin-left: 20px;
  font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
    "Lucida Sans", Arial, sans-serif;
}

.question-title {
  margin: 10px 0 0 20px;
  font-size: 25px;
  font-weight: 700;
  line-height: 2.5;
  color: #333;
  text-align: left;
  word-wrap: break-word;
}

.question-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #eee;
  padding-top: 20px;
  margin-top: 10px;

  .left,
  .right {
    display: flex;
    flex-direction: row;
    gap: 10px;
    padding: 0 10px;
  }

  .left {
    width: 100%;
    justify-content: start;
  }

  .right {
    width: 100%;
    justify-content: end;
  }
}

.question-bottom img {
  height: 25px;
  width: 25px;
  margin: 6px;
}

.question-bottom img:hover {
  cursor: pointer;
}

.ghost {
  border: solid 1px rgb(19, 41, 239);
}
.chosenClass {
  background-color: #f1f1f1;
}

.list-group-item {
  margin-bottom: 10px;
}

.output-item {
  display: flex;
  height: 40px;
  align-items: center;
}

.output-icon {
  height: 20px;
  width: 20px;
  margin-right: 10px;
}

.output-info {
  font-size: 14px;
  color: #666;
}

.dialog-hint {
  font-size: 20px;
  color: #606266;
  margin-bottom: 30px;
  text-align: left;
  line-height: 1.5;
}

.edit-title{
  text-align: left;
  font-size: 18px;
  font-weight: 700;
  line-height: 3;
  color: #303133;
}

.publish-form-item{
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
  height: 60px;
}

.publish-form-info{
  min-width: 200px;
  text-align: left;
}
</style>
